#!/usr/bin/python
# -*- coding:utf-8 -*-

import urllib
import os
import cPickle
from dateutil.parser import parse
from time import mktime,time,sleep

#各APIを使用するために必要なAPIキー
API_Key={
    "YahooJapan":"LinkTest"
    ,"Flickr":"b72a056d379a064ad407551c941d75be"
    ,"KakakuCom" : "2a9157100cf99a5fd54079c237db0577"
    }

def StrToTime(timestring):
    return mktime(parse(timestring).timetuple())

def Download(url,data=None):
    #dbname="download.db"
    #db=dict() if not os.path.exists(dbname) else cPickle.loads(file(dbname,"r").read())
    #if not (db.has_key(url) and db[url]["time"]-time()<86400):
        #html=urllib.urlopen(url).read()
        #db[url]={"html":html,"time":time()}
        #file(dbname,"w").write(cPickle.dumps(db))
    #return db[url]["html"]
    for i in xrange(5):
        try:
            return urllib.urlopen(url,data).read()
        except:
            sleep(5)
    return ""

def JapaneseConsole(unicodeString):
    '''日本語をコンソールに出力する際のラッパー'''
    if os.name =="nt":
        return unicodeString
    elif os.name =="posix":
        return unicodeString.encode("utf-8")

def Trim(string,additinal=u""):
    trimstr=u" \t\r\n\x0B　"
    if(additinal!=""): trimstr+=additinal
    return string.strip(trimstr)

def PrintDict(d):
    for k,v in sorted(d.iteritems(),key=lambda kv: kv[1],reverse=True):
        print JapaneseConsole(k),v
    
